package com.guoxin.concurrentprogramming.chapter3.deadlock;

/**
 * @author guoxin
 * @date 2019/7/17
 */
public class DeadLock extends Thread {
    private Object tool;
    private static final Object FORK1 = new Object();
    private static final Object FORK2 = new Object();

    public DeadLock(Object tool){
        this.tool = tool;
        if(tool== FORK1){
            this.setName("哲学家1");
        }
        if(tool== FORK2){
            this.setName("哲学家2");
        }
    }

    @Override
    public void run() {
        if(tool== FORK1){
            synchronized (FORK1){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (FORK2){
                    System.out.println("哲学家A开始吃饭");
                }
            }
        }

        if(tool== FORK2){
            synchronized (FORK2){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (FORK1){
                    System.out.println("哲学家B开始吃饭");
                }
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        DeadLock a= new DeadLock(FORK1);
        DeadLock b= new DeadLock(FORK2);
        a.start();
        b.start();
        Thread.sleep(1000);
    }
}
